/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_components/zhiqim_manager.htm
 *
 * Zhiqim Manager is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
+(function(Z)
{//BEGIN

/**************************************************/
//定义全局的对象，便于所有的页面调用
/**************************************************/
var Zin = window.Zin = {};

Zin.getLocationOrigin = function()
{//location.origin在ie中的兼容性处理
    if (window.location.origin) 
        return window.location.origin;
        
    return window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
};

Zin.doClickChildMenu = function(elem, menuUrl)
{//点击二级栏目
    var $elem = Z(elem);
    
    //1.判断是否已存在，存在则置为显示并切换该框架导航选项卡置为活动
    var elemId = $elem[0].id || "menu_" + Z.Ids.uuid();
    $elem.attr("id", elemId);
    
    var tabId = "tab_" + elemId;
    var iframeId = "iframe_" + elemId;
    var $tab = Z("#" + tabId);
    var $iframe = Z("#" + iframeId);
    
    if ($tab[0] && $iframe[0])
    {
        Zin.selectIframeTab(elemId);
        return;
    }
    
    //2.不存在则创建该框架导航选项卡
    var $tabList = Z(".iframenav-tab-list");
    var clickText = $elem.attr("data-text") || $elem.text() || "未命名";
    $tab = Z('<li class="iframenav-tab-item" id="'+ tabId +'"><span>'+ clickText +'</span><i class="z-font z-error"></i></li>')
           .appendTo($tabList);
    $tab.on("click", Zin.selectIframeTabEvent);
    $tab.find(".z-refresh").on("click", Zin.refreshIframeTabClick);
    $tab.find(".z-error").on("click", Zin.closeIframeTabClick);

    $iframe = Z('<div id="'+ iframeId +'" class="iframenav-cont-item"><iframe src="'+ menuUrl +'" name="'+iframeId+'"></iframe></div>')
              .appendTo(".iframenav-cont");

    //3.选中自己，调整位置偏移，显示完整选项卡
    Zin.selectIframeTab(elemId);
};

/**************************************************/
//3个iframenav的点击事件（其中刷新暂时没有添加）
/**************************************************/

Zin.selectIframeTabEvent = function(event)
{//点击选项卡标签页
    var $tab = Z.E.current(event);
    var tabId = $tab.id;
    Zin.selectIframeTab(tabId.replace("tab_", ""));
};

Zin.refreshIframeTabClick = function(event)
{//点击选项卡上的刷新按钮
    var $refresh = Z(Z.E.current(event));
    var tabId = $refresh.parent()[0].id;
    Zin.refreshIframeTab(tabId.replace("tab_", ""));
};

Zin.closeIframeTabClick = function(event)
{//点击选项卡上的关闭按钮
    var $close = Z(Z.E.current(event));
    var tabId = $close.parent()[0].id;
    Zin.closeIframeTab(tabId.replace("tab_", ""));
};

/**************************************************/
//指定操作功能
/**************************************************/

Zin.selectIframeTab = function(id)
{//选择指定的选项卡
    Z("#tab_"+id).addClass("active").siblings(".iframenav-tab-item").removeClass("active");
    Z("#iframe_"+id).addClass("active").siblings(".iframenav-cont-item").removeClass("active");
    Zin.setTranslateForShowActive();
    
    var mainUrl = Z("#iframe_"+id+" iframe").attr("src");
    if (mainUrl)
    {//切换选项卡同步到后端，关闭选项卡时为null不处理，整页刷新时依然使用关闭的URL
        var $elem = Z("#" + id);
        $elem.parent().parent().find("li").removeClass("active");
        $elem.addClass("active");
    
        mainUrl = mainUrl.substring(Zin.getLocationOrigin().length);
        Z.ajax("sessionUser", "setMainUrl").addParam(mainUrl).execute();
    }
};

Zin.refreshIframeTab = function(id)
{//刷新指定框架
    Z("#iframe_" + id).find("iframe")[0].contentWindow.location.reload(true);
};

Zin.closeIframeTab = function(id)
{//关闭指定框架，并切换到前一个框架
    var $currTab = Z("#tab_" + id);
    var $prevTab = Z($currTab[0].previousElementSibling || Z(".iframenav-tab-item:first-child")[0]);

    //删除当前框架，同时选中前一个为活动
    Zin.closeIframeTabOnly(id);
    Zin.selectIframeTab($prevTab[0].id.replace("tab_", ""));
};

Zin.closeIframeTabOnly = function(id)
{//仅关闭指定框架
    Z("#tab_" + id).remove();
    Z("#iframe_" + id).remove();
};

Zin.setTranslateForShowActive = function()
{//调整位置偏移，显示完整选项卡
    var $tabList = Z(".iframenav-tab-list");
    var $tabs = Z(".iframenav-tab-item");
    
    //1.校准宽度
    var fillWidth = 0;
    $tabs.each(function(item){
        fillWidth += item.getBoundingClientRect().width;
    });
    fillWidth = Math.ceil(fillWidth);
    
    var wrapRect = Z(".iframenav-tab-wrap")[0].getBoundingClientRect();
    $tabList.css("width", fillWidth > wrapRect.width ? fillWidth : wrapRect.width);
    if (fillWidth < wrapRect.width)
        $tabList.css("transform", "translate(0,0)");

    //2.当前标签、前后两个标签，宽度信息
    var $active = Z(".iframenav-tab-item.active");
    var activeRect = $active[0].getBoundingClientRect();
    var $prev = $active[0].previousElementSibling;
    var prevWidth = !!$prev ? $prev.getBoundingClientRect().width : 0;
    var $next = $active[0].nextElementSibling;
    var nextWidth = !!$next ? $next.getBoundingClientRect().width : 0;
    
    //3.计算理论偏移量
    var mLeft = activeRect.left - prevWidth - wrapRect.left;
    var mRight = activeRect.right + nextWidth - wrapRect.right;
    var tabTransX = parseFloat($tabList.css("transform").replace(/^[^\d]+/,"") || 0);
    tabTransX = tabTransX >= 0 ? tabTransX : 0;
    if (mLeft < 0 && mRight > 0)
        return;
        
    if (mLeft < 0)
        tabTransX += mLeft;
        
    if (mRight > 0)
        tabTransX += mRight;
        
    $tabList.css("transform", "translate(-" + tabTransX + "px,0)");
};

/**************************************************/
//外部调用
/**************************************************/

Zin.toggleIframeCtrlWrap = function()
{//切换关闭操作界面
    Z(".iframenav-ctrl-wrap").toggle();
};

Zin.selectIframeTabActive = function()
{//定位到当前选项卡
    var $active = Z(".iframenav-tab-item.active");
    var tabId = $active[0].id;
    Zin.selectIframeTab(tabId.replace("tab_", ""));
    
    Zin.toggleIframeCtrlWrap();
}

Zin.closeIframeTabAll = function()
{//关闭所有选项卡
    var $tab = Z(".iframenav-tab-item:not(:first-child)");
    
    var idList = [];
    $tab.each(function(elem){idList.push(elem.id.replace("tab_", ""));});
    idList.forEach(Zin.closeIframeTabOnly);
    
    //选中首页
    Zin.toggleIframeCtrlWrap();
    var $index = Z(".iframenav-tab-item:first-child");
    Zin.selectIframeTab($index[0].id.replace("tab_", ""));
};

Zin.closeIframeTabOther = function()
{//关闭其他选项卡
    var $tab = Z(".iframenav-tab-item:not(:first-child)");
    var $active = Z(".iframenav-tab-item.active");
    
    var idList = [];
    $tab.each(function(elem){if ($active[0] !== elem){idList.push(elem.id.replace("tab_",""));}});
    idList.forEach(Zin.closeIframeTabOnly);
    
    Zin.toggleIframeCtrlWrap();
    Zin.setTranslateForShowActive();
};

Zin.refreshIframeTabActive = function()
{//刷新当前选项卡
    var $active = Z(".iframenav-tab-item.active");
    Zin.refreshIframeTab($active[0].id.replace("tab_",""));
};

Zin.turnIframeTab = function(isNext)
{//向前向后翻页选项卡
    var wrapWidth = Z(".iframenav-tab-wrap")[0].getBoundingClientRect().width;
    var $tabList = Z(".iframenav-tab-list");
    var tabTransX = parseFloat($tabList.css("transform").replace(/^[^\d]+/,"") || 0);
    tabTransX = tabTransX >= 0 ? tabTransX : 0;
    
    var $tabs = Z(".iframenav-tab-item");
    var listWidth = 0, fillWidth = 0;
    var fillArray=[];
    
    for (var i=0;i<$tabs.length;i++)
    {
        var tab = $tabs[i];
        var tabWidth = tab.getBoundingClientRect().width;
        listWidth += tabWidth;
        if (isNext)
        {
            if (listWidth - tabTransX > wrapWidth)
            {
                tabTransX = listWidth - tabWidth;
                break;
            }
        }
        else
        {
            fillArray.unshift(tabWidth);
            if (listWidth >= tabTransX)
            {
                while(fillWidth < wrapWidth)
                {
                    fillWidth += fillArray[i++];
                }
                tabTransX = listWidth - fillWidth;
                break;
            }
        }
    }
    
    $tabList.css("transform", "translate(-" + (tabTransX >= 0 ? tabTransX : 0) + "px,0)");
}

//END
})(zhiqim);